<template>
	<view>
		<uni-nav-bar ref="navBar" fixed statusBar title="分组管理" :border="false" backgroundColor="#ffffff"
			@clickLeft="goBack">
			<template v-slot:left>
				<image class="size-32" src="@/static/svg/icon-back.svg" />
			</template>
		</uni-nav-bar>
		<view class="group-name">
			<view class="group-title">分组名称</view>
			<view class="input-name flex item-center justify-between">
				<input type="text" placeholder="*请填写分组名称" v-model="groupName" :maxlength="16" :disabled="teemDec.defaultState == 2" class="name-show-box">
				<image src="../../../static/svg/icon-input-clean.svg" mode="widthFix" :style="{width:'20px'}" @click="cleanText" v-if="groupName.length && teemDec.defaultState != 2"></image>
				<text>{{groupName.length}}/16</text>
			</view>
		</view>
		<view class="group-name" v-if="teemDec.defaultState != 2">
			<view class="group-title">分组佣金</view>
			<view class="commission-name flex item-center justify-between">
				<input :value="commissionRate" @change="inputChange($event)" />
				<view class="w-40 h-full flex center pl-16" style="border-left:1px solid rgba(51, 51, 51, 0.30);">
					<text>%</text>
				</view>
			</view>
			<view class="mt-8 tip">佣金优先级：专属佣金>分组佣金>活动佣金</view>
		</view>
		<view :style="{'height':groupH}">
			<view class="group-name"  >
				<view class="group-title flex justify-between item-center">
					<view>分组成员</view>
					<view style="color: #FA4543;" @click="linkHomePage" v-if="teemDec.defaultState != 2 && list.length">+添加成员</view>
				</view>
        <view v-if="teemDec.defaultState != 2 && list.length" class="flex item-center batch-text" @click="changeCheck">
					<image v-if="check" class="size-16 mr-4" src="@/static/svg/checkbox-checked.svg"></image>
					<image v-else class="size-16 mr-4" src="@/static/svg/checkbox-default.svg"></image>
					批量操作
				</view>
				<scroll-view scroll-y="true" :style="{'max-height':h}" @scrolltolower='scrolltolower' refresher-enabled='true'
					:refresher-triggered="triggered" @refresherrestore="onRestore" @refresherrefresh="onRefresh">
					<view v-for="item,index in list" class="agent-box flex item-center" :key="item.id" >
						<view v-if="check" class="mr-4" @click="item.check = !item.check">
							<image v-if="item.check" class="size-14" src="@/static/svg/activity/icon-radio-check-blue.svg"></image>
							<image v-else class="size-14" src="@/static/svg/activity/icon-radio-default.svg"></image>
						</view>
						<image :src="item.avatar" mode="" class="img-avatar"></image>
						<view class="agent-info flex flex-col justify-between">
							<view class="nick-name">
								{{item.nickName}}
							</view>
							<view class="total-settle">已分销：<text class="red-price">¥{{item.totalOrderAmt}}</text>（共{{item.totalOrderCount}}单）</view>
						</view>
						<uni-icons type="trash" size="20" color="rgba(51, 51, 51, 0.6)" @click="delItem(item)" v-if="teemDec.defaultState != 2"></uni-icons>
					</view>
				</scroll-view>
				<view class="add-grouper" @click="linkHomePage" v-if="teemDec.defaultState != 2 && !list.length">添加成员</view>
			</view>
		</view>
		<view class="flex item-center justify-between" v-if="teemDec.defaultState != 2">
			<template v-if="check">
				<view class="del-btn" @click="patchMove" v-if="params.groupId">批量移动</view>
				<view class="batch-btn" @click="patchDel" v-if="params.groupId">批量删除</view>
			</template>
			<template v-else>
				<view class="del-btn" @click="delGroup" v-if="params.groupId">删除分组</view>
				<view class="release-btn" @click="submitGroup"
				 :class="{'unactive':((!groupName && !list.length) || teemDec.defaultState == 2)}" :style="{width:params.groupId?'45%':'100%'}">保存</view>
			</template>
		</view>
		<GroupPopup ref="popup" :currentGroupId="params.groupId" @onSubmit="getList" />
	</view>
</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		ref,
		getCurrentInstance
	} from 'vue'
	import {
		pageGroupAgent,
		saveGroup,
		deleteGroupAgent,
		deleteGroup,
		batchChangeGroup
	} from '@/pagesD/api/group.js'
	import {
		mathHeight,
		modelShowToast,
		formatMoneyInput
	} from '@/utils/index.js'
	import GroupPopup from '../components/GroupPopup.vue'
	const h = ref(0)
	h.value = mathHeight(390)
	const groupH = ref(0)
	groupH.value = mathHeight(340)
	const groupName = ref('')
	const commissionRate = ref('')
	const triggered = ref(false)
	const teemDec = ref({})
	const check = ref(false)
	let list = ref([])
	let total = ref(0)
	let getOpenerEventChannel = ref(null)
	let ids = []
	const params = ref({
		groupId: '',
		pageNum: 1,
		pageSize: 15
	})
	const popup = ref(null)
	const changeCheck = () => {
		check.value = !check.value
	}
	const cleanText = () => {
		groupName.value = ''
	}
	const inputChange = ({ detail }) => {
		if(detail.value){
			commissionRate.value = formatMoneyInput(detail.value, 100)
		}else{
			commissionRate.value = 0
		}
	}
	const getList = async () => {
		triggered.value = true
		uni.showLoading()
		let result = await pageGroupAgent(params.value)
		if (result) {
			result.list.forEach(item => {
				item.check = false
			})
			list.value = params.value.pageNum == 1 ? result.list : (list.value).concat(result.list)
			total.value = result.total
		}
		uni.hideLoading()
		triggered.value = false
	}
	const scrolltolower = () => {
		if (list.value.length >= total.value) {
			return
		}
		params.value.pageNum = params.value.pageNum + 1
		getList()
	}
	const onRestore = () => {
		// setTimeout(() =>{
		triggered.value = false; // 需要重置
		// },2000)
		// console.log("onRestore");
	}
	const reFresh = () => {
		list.value = []
		params.value.pageNum = 1
		getList()
	}
	const onRefresh = () => {
		triggered.value = true
		reFresh()
	}
	const delItem = (item) => {
		modelShowToast({
			content:'确认删除该成员'
		},
		async () =>{
			let result = await deleteGroupAgent(item.id)
			if(result){
				reFresh()
			}
		})
	}
	const patchMove = () => {
		ids = []
		list.value.forEach(item => {
			if(item.check){
				ids.push(item.userId)
			}
		})
		if(!ids.length) return uni.showToast({icon: 'none',title: '请选择分组成员'})
		popup.value && popup.value.showPopup(true, ids)
	}
	const patchDel = () => {
		ids = []
		list.value.forEach(item => {
			if(item.check){
				ids.push(item.userId)
			}
		})
		if(!ids.length) return uni.showToast({icon: 'none',title: '请选择分组成员'})
		modelShowToast({
				content:'确认从该分组删除经纪人？'
			},
			async () =>{
				let result = await batchChangeGroup({groupId: 0, userIds: ids})
				if(result){
					reFresh()
				}
			})
	}
	const goBack = () => {
		if(getCurrentPages().length === 1) {
			uni.reLaunch({
				url: '/pages/home/home'
			})
			return
		}
		getOpenerEventChannel.value.emit('reFreshPage','refresh')
		uni.navigateBack()
	}
	const delGroup = () =>{
		modelShowToast({
			content:'确定删除该分组？'
		},
		async () =>{
			uni.showLoading()
			// let result = await deleteGroup(params.value.groupId)
			deleteGroup(params.value.groupId).then(res => {
				uni.hideLoading()
				setTimeout(()=> {
					uni.showToast({
						icon: 'none',
						title: '删除成功'
					})
					setTimeout(()=>{
						goBack()
					},1500)
				},500)
			}).catch(err => {
				// uni.hideLoading()
				setTimeout(()=> {
					uni.showToast({
						icon: 'none',
						title: err.message
					})
				},500)
			})
			
		})
	}
	const submitGroup = async () => {
		if(!groupName.value){
			uni.showToast({
				icon: 'none',
				title: '请输入分组名称'
			})
			return
		}
		// if(!list.value.length){
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '请选择分组成员'
		// 	})
		// 	return
		// }
		uni.showLoading()
		// let userIds = list.value.map(item => {
		// 	return item.id
		// })

		let obj = {
			groupName:groupName.value,
			commissionRate: commissionRate.value
			// userIds:userIds.join(',')
		}
		if(params.value.groupId){
			obj.id = params.value.groupId
		}
		let result = await saveGroup(obj)
		uni.hideLoading()
		if(result){
			setTimeout(()=> {
				uni.showToast({
					icon: 'none',
					title:'保存成功'
				})
				setTimeout(()=>{
					goBack()
				},1500)
			},500)
			
		}else{
			uni.showToast({
				icon: 'none',
				title: '保存失败，请稍后再试'
			})
		}
	}
	const linkHomePage = () => {
		if(!groupName.value){
			uni.showToast({
				icon: 'none',
				title: '请输入分组名称'
			})
			return
		}
		uni.navigateTo({
			url:"/pagesD/group-manage/member-list/member-list",
			events: {
				reFreshPage: (data) => {
					if(data && data.id){
						params.value.groupId = data.id
						reFresh()
					}
				}
			},
			success:(res) => {
				let query = {groupName:groupName.value, commissionRate: commissionRate.value}
				if(params.value.groupId){
					query.id = params.value.groupId
				}
				res.eventChannel.emit('acceptData',query)
			}
		})
	}

	onLoad((query) => {
		getOpenerEventChannel.value = getCurrentInstance().ctx.getOpenerEventChannel();
		if (query.id) {
			params.value.groupId = query.id
			getList()
		}
		getOpenerEventChannel.value.on('acceptData',data => {
			groupName.value = data.data.groupName
			commissionRate.value = data.data.commissionRate
			teemDec.value = data.data
		})
	})
</script>

<style scoped lang="scss">
	.group-name {
		padding: 14px;
		background-color: #ffffff;
		margin-top: 2px;
	}

	.group-title {
		font-size: 14px;
		font-weight: 600;
		line-height: 20px;
		color: rgba(51, 51, 51, 1);
	}

	.input-name {
		width: 100%;
		height: 44px;
		padding: 12px 16px;
		border-radius: 8px;
		background: rgba(245, 245, 245, 1);
		font-size: 14px;
		font-weight: 400;
		line-height: 20px;
		color: rgba(51, 51, 51, 0.6);
		margin-top: 10px;
		.name-show-box{
			height: 44px;
			width: calc(100% - 80px);
		}
	}
	.commission-name {
		width: 50%;
		height: 44px;
		padding: 0 16px;
		border-radius: 8px;
		font-size: 14px;
		font-weight: 400;
		line-height: 20px;
		color: rgba(51, 51, 51, 0.6);
		border: 1px solid rgba(51,51,51,0.2);
		margin-top: 10px;
	}
	
	.tip{
		color: rgba(51,51,51,0.6);
		font-size: 12px;
	}

	.add-grouper{
		// width: Fixed (343px)
		height: 46px;
		padding: 12px 53px;
		border-radius: 8px;
		border: 1px solid rgba(250, 69, 67, 1);
		color: rgba(250, 69, 67, 1);
		text-align: center;
		margin-top: 10px;
	}

	.del-btn{
		width: 45%;
		height: 46px;
		padding: 12px, 20px, 12px, 20px;
		border-radius: 8px;
		margin: 5px 20px;
		text-align: center;
		line-height: 46px;
		color: rgba(0, 174, 255, 1);
		border:1px solid rgba(0, 174, 255, 1);
		background: #ffffff;
	}
  .batch-text{
    color: #9B9B9B;
    margin: 8px 0;
  }
	.batch-btn{
		width: 45%;
		height: 46px;
		padding: 12px, 20px, 12px, 20px;
		border-radius: 8px;
		margin: 5px 20px;
		text-align: center;
		line-height: 46px;
		color: #FA4543;
		border:1px solid #FA4543;
		background: #ffffff;
	}
	.agent-box {
			padding: 8px 0px;
			// margin: 0 20px 20px;
			background-color: #ffffff;
			border-radius: 8px;

			.agent-info {
				width: calc(100% - 80px);
				margin-left: 10px;
				height: 45px;
			}

			.img-avatar {
				width: 45px;
				height: 45px;
				border-radius: 8px;
			}

			.icon-list {
				width: 16px;
				height: 16px;
				margin-left: 4px;
			}

			.nick-name {
				font-size: 14px;
				font-weight: 400;
				line-height: 20px;
			}

			.total-settle {
				font-size: 12px;
				font-weight: 400;
				// line-height: 17px;
				color: rgba(51, 51, 51, 0.6);
			}

			.red-price {
				color: rgba(250, 69, 67, 1);
			}
			.group-name{
				font-size: 12px;
				background-color: rgba(250, 69, 67, 0.6);
				padding: 0 4px;
				color: #ffffff;
				margin-left: 4px;
			}
		}
		.release-btn {
			// width: 343px;
			height: 46px;
			padding: 12px, 20px, 12px, 20px;
			border-radius: 8px;
			// gap: 10px;
			background: #FA4543;
			color: #ffffff;
			margin: 5px 20px;
			text-align: center;
			line-height: 46px;
			&.unactive{
				background: rgba(250, 69, 67, 0.6);
			}
		}
</style>
